<?php


namespace map;


use custom\Curl;
use custom\Err;
use custom\Log;
use think\Exception;

class GaoDe {
    protected static $configs = [
        'key' => 'f55d9a2cb8a0ac82738cf07731cbef1c',
        'url' => 'https://restapi.amap.com/v3/',
    ];

    /**
     * 逆地理编码-通过经纬度获取地址信息
     * @param $lat 纬度
     * @param $lon 经度
     * @param $lang 语言
     * @return bool
     * @throws Exception
     */
    public static function getByLocation($lat, $lon, $lang) {
        $url = 'geocode/regeo';
        $urlData = [
            'location' => "{$lon},{$lat}",
            //            'language' => $lang,
        ];
        $url .= "?".http_build_query($urlData);
        if(!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'gaodeMapData.log');
        return $res;
    }

    /**
     * 获取poi
     * @param $address
     * @param $city
     * @param string $tag
     * @param int $offset
     * @return bool
     * @throws Exception
     */
    public static function getPoi($address, $city, $tag = '住宅', $offset = 20) {
        $url = 'place/text';
        $urlData = [
            'keywords'   => $address,
            'types'      => $tag,
            'city'       => $city,
            'children'   => 1,
            'offset'     => $offset,
            'page'       => 1,
            'extensions' => 'all'
        ];
        $url .= "?".http_build_query($urlData);
        if(!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'gaodeMapData.log');
        return $res;
    }

    /**
     * 地理编码-通过地址获取信息
     * @param $address
     * @param string $city
     * @return bool
     * @throws Exception
     */
    public static function getByAddress($address, $city = '') {
        $url = 'geocode/geo';
        $urlData['address'] = $address;
        $city == '' && $urlData['city'] = $city;
        $url .= "?".http_build_query($urlData);
        if(!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'gaodeMapData.log');
        return $res;
    }


    /**
     * 百度地图调用
     * @param $url
     * @param array $data
     * @param string $mth
     * @return bool
     * @throws Exception
     */
    public static function request($url, $data = [], $mth = 'GET') {
        $conf = self::$configs;
        $url = $conf['url'].$url.(strpos($url, '?') ? '&' : '?')."key={$conf['key']}&output=json";
        $res = Curl::getInstance()->xhr($mth, $url, $data);
        Log::write("map|$url|".json_encode($data).'|res:'.json_encode($res), 'gaode_map.log');
        if(empty($res)) {
            Err::add('地图获取失败');
            return false;
        }
        $res = json_decode($res, true);
        if(!isset($res['status'])) {
            Err::add('地图获取失败');
            return false;
        }
        if($res['status'] != 1) {
            Err::add('地图获取失败');
            return false;
        }

        return $res;
    }
}